from typing import Tuple, Union

from app.models.data_base_models import PlatformView
from app.services import get_base_session


class PlatformViewServices:
    @staticmethod
    def get_platform_views() -> Tuple[bool, Union[list[PlatformView], str, None]]:
        session = get_base_session()
        try:
            res = session.query(PlatformView).all()
            return True, res
        except Exception as e:
            return False, str(e)
        finally:
            session.close()


    @staticmethod
    def get_platform_view_by_ids(ids: list[int]) -> Tuple[bool, Union[list[PlatformView], str]]:
        if ids is None or len(ids) == 0:
            return False, "ids cannot be empty"
        session = get_base_session()
        try:
            res = session.query(PlatformView).filter(PlatformView.id.in_(ids)).all()
            return True, res
        except Exception as e:
            return False, str(e)
        finally:
            session.close()


    @staticmethod
    def delete_platform_view_by_id(view_id) -> Tuple[bool, str]:
        session = get_base_session()
        try:
            session.query(PlatformView).filter(PlatformView.id == view_id).delete()
            session.commit()
            return True, "succeed delete"
        except Exception as e:
            return False, str(e)
        finally:
            session.close()


    @staticmethod
    def add_platform_view(viewname:str, viewurl:str, parentId:int, ismenu: int, orderKey: int) -> Tuple[bool, str]:
        session = get_base_session()
        try:
            view = PlatformView(
                view_name = viewname,
                parent_id = parentId,
                view_url = viewurl,
                is_menu = ismenu,
                order_key = orderKey
            )
            session.add(view)
            session.commit()
            return True, "succeed add"
        except Exception as e:
            return False, str(e)
        finally:
            session.close()


    @staticmethod
    def edit_platform_view(platformView:PlatformView) -> Tuple[bool, str]:
        session = get_base_session()
        try:
            oldPlatformView = session.query(PlatformView).filter(PlatformView.id == platformView.id).first()
            if oldPlatformView is None:
                return False, "指定id的页面不存在"
            oldPlatformView.view_name = platformView.view_name
            oldPlatformView.view_url = platformView.view_url
            oldPlatformView.is_menu = platformView.is_menu
            oldPlatformView.order_key = platformView.order_key
            oldPlatformView.parent_id = platformView.parent_id
            session.commit()
            return True, "succeed edit"
        except Exception as e:
            return False, str(e)
        finally:
            session.close()